package com.example;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

public class ExcelUpdater {

    public static void updateExcelWithMetadata(String excelPath, List<Map<MetadataType, String>> metadataList)
            throws IOException {

        try (FileInputStream inputStream = new FileInputStream(excelPath)) {
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            // 添加标题行（如果不存在）
            Row headerRow = sheet.getRow(0);
            if (headerRow == null) headerRow = sheet.createRow(0);

            // 设置标题
            for (MetadataType type : MetadataType.values()) {
                Cell headerCell = headerRow.createCell(type.getColumnIndex());
                headerCell.setCellValue(type.getMetaName());
            }

            // 填充数据行
            for (int rowNum = 1; rowNum <= metadataList.size(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row == null) row = sheet.createRow(rowNum);

                Map<MetadataType, String> metadata = metadataList.get(rowNum - 1);
                for (MetadataType type : MetadataType.values()) {
                    Cell cell = row.createCell(type.getColumnIndex());
                    cell.setCellValue(metadata.getOrDefault(type, "Error"));
                }
            }

            // 保存更新
            try (FileOutputStream outputStream = new FileOutputStream(excelPath)) {
                workbook.write(outputStream);
            }
        }
    }
}